package de.pd.pically.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;

import de.pd.pically.util.ImageUtil;

public class JFileChooserPreview {
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
		}

		final JFrame frame = new JFrame();
		JButton button = new JButton("Open File Chooser");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = new JFileChooser();
				PreviewPane previewPane = new PreviewPane();
				chooser.setAccessory(previewPane);
				chooser.addPropertyChangeListener(previewPane);
				chooser.showDialog(frame, "OK");
			}
		});
		frame.getContentPane().add(button);

		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}

	@SuppressWarnings("serial")
	static class PreviewPane extends JPanel implements PropertyChangeListener {
		private JLabel label;
		private int maxImgWidth;

		public PreviewPane() {
			setLayout(new BorderLayout(5, 5));
			setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
			add(new JLabel("Preview:"), BorderLayout.NORTH);
			label = new JLabel();
			label.setBackground(Color.WHITE);
			label.setOpaque(true);
			label.setPreferredSize(new Dimension(200, 200));
			maxImgWidth = 195;
			label.setBorder(BorderFactory.createEtchedBorder());
			add(label, BorderLayout.CENTER);
		}

		public void propertyChange(PropertyChangeEvent evt) {
			Icon icon = null;
			if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt
					.getPropertyName())) {
				File newFile = (File) evt.getNewValue();
				if (newFile != null && newFile.isFile()) {
					String path = newFile.getAbsolutePath();
					icon = ImageUtil.getThumbnail(path, maxImgWidth);
				}

				label.setIcon(icon);
				this.repaint();

			}
		}

	}

}